package cn.tedu.v3;

import java.io.*;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * Version 3.0 多人聊天室 双向互通
 * 步骤：1.找到start启动方法，增加一个线程【lambda表达式】控制读
 *      2.定义读写，统一写在一起，读写功能，按照顺序定义排序！
 *      3.定义和功能分开，目的：增加可读性，保障逻辑顺序一致！
 *      4.读入功能增加到线程当中。
 */
public class Client {
    private Socket socket;


    public Client() {
        try {
            socket = new Socket("127.0.0.1", 6666);
        } catch (NullPointerException e) {
            System.out.println("友情提示：IP传入错误导致链接失败~");
        } catch (UnknownHostException e) {
            System.out.println("友情提示：IP传入错误");
        } catch (ConnectException e) {
            System.out.println("客户端链接失败：建议检查IP或者端口号");
        } catch (IOException e) {
            System.out.println("客户端链接服务器失败：检查IP/端口");
        }
    }

    public void start() {
        PrintWriter pw = null;
        // BufferedReader br=null; //置空：赋值、关流
        try {
            //2.定义写出：客户端输出流
            pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);
            //1.定义读入：客户端输入流，目的：代码可读性
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));


            new Thread(() -> {
                try {
                    //2.2读入功能：①置空,不加，确定message一定读取数据
                    String message;
                    //②读取服务器发来的消息:读入的一行不为空，一直有数据
                    //br.readLine()读取一行
                    while ((message = br.readLine()) != null) {
                        System.out.println("服务器端说：" + message);
                        System.out.println("客户端请输入：");
                    }
                } catch (IOException e) {
                    System.out.println("服务器端读入失败了！");
                }
            }).start();
            //1.1写出功能
            Scanner input = new Scanner(System.in);
            while (true) {
                System.out.println("客户端请输入：");
                String line = input.nextLine();
                pw.println("客户端说："+line); //发给服务器
                System.out.println("写出成功。");
            }
        } catch (UnsupportedEncodingException e) {
            System.out.println("客户端/服务器端编码集有问题！");
        } catch (IOException e) {
            System.out.println("客户端链接服务器端：IO流操作出现错误！");
        } finally {
            if (pw != null)
                pw.close();
            if (socket != null && !socket.isClosed()) {
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("通讯关闭失败");
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        Client client = new Client();
        client.start();
    }

    }

